package com.itheima.practice.demo04;

public class Ticket implements Runnable {
    private int ticket = 10;
    private Object obj = new Object();
    @Override
    public void run() {
        while (true) {
            if ("窗口一".equals(Thread.currentThread().getName())) {
                //同步方法
                boolean b = synchronizedMethod();
                if (b) {
                    break;
                }
            }
            if ("窗口二".equals(Thread.currentThread().getName())) {
                synchronized (obj) {
                    if (ticket <= 0) {
                        break;
                    }else {
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        ticket--;
                        System.out.println(Thread.currentThread().getName() + "正在卖票，还剩" + ticket +"张票");
                    }
                }
            }
        }
    }

    private boolean synchronizedMethod() {
        if (ticket <= 0) {
            return true;
        }else {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ticket--;
            System.out.println(Thread.currentThread().getName() + "正在卖票，还剩" + ticket +"张票");
            return false;
        }
    }
}
